<!DOCTYPE html>
<html>
<head>
<script src="../../resources/js-test.js"></script>
<script src="resources/common.js"></script>
</head>
<body>
<p id="description"></p>
<div id="console"></div>

<script>
description("Tests crypto.subtle.encrypt() using a BufferSource that was neutered (prior to encrypt())");

jsTestIsAsync = true;

data = null;
key = null;

var keyData = hexStringToUint8Array("2b7e151628aed2a6abf7158809cf4f3c");
var iv = hexStringToUint8Array("000102030405060708090a0b0c0d0e0f");
var kExpectedCipherTextHex = "c84af0b613435d5d9182801a9bd9320b";

var extractable = true;
var usages = ['encrypt', 'decrypt'];

debug("Importing key...");
crypto.subtle.importKey('raw', keyData, "aes-cbc", extractable, usages).then(function(result) {
    key = result;

    debug("\nEncrypting empty plaintext (as a control group)...");
    return crypto.subtle.encrypt({name: "aes-cbc", iv: iv}, key, new Uint8Array());
}).then(function(result) {
    bytesShouldMatchHexString("Encryption", kExpectedCipherTextHex, result);

    debug("\nCreating ArrayBuffer...");
    plainText = new ArrayBuffer(1000);
    shouldBe("plainText.byteLength", "1000");

    debug("Neutering plainText...");
    try { postMessage(plainText, "xxx", [plainText]); } catch (e) { }
    shouldBe("plainText.byteLength", "0");

    debug("\nEncrypting neutered plaintext...");
    return crypto.subtle.encrypt({name: "aes-cbc", iv: iv}, key, plainText);
}).then(function(result) {
    bytesShouldMatchHexString("Encryption", kExpectedCipherTextHex, result);
}).then(finishJSTest, failAndFinishJSTest);
</script>

</body>
</html>
